import classNames from 'classnames'
import React, {
  useRef,
  useState,
  useEffect,
  useImperativeHandle,
  forwardRef,
  useContext,
} from 'react'
import { EventContext } from '@/app/(dabao)/chatStreem/components/footerInput'
interface Props {
  nodeProps?: React.HTMLProps<HTMLTextAreaElement>
  className?: string
  [key: string]: any
}
export interface TextareaHandles {
  clearValue: () => void
  getValue: () => string
  setValue: (newValue: string) => void
}
/* eslint-disable react/display-name */
const AutoResizeTextarea = forwardRef((props: Props, ref) => {
  const textareaRef = useRef<HTMLTextAreaElement>(null)
  const sendMsg = useContext(EventContext)
  const [value, setValue] = useState('')
  const classes = classNames(
    'w-[88%]  border-none outline-none border-[#e5e7eb] resize-none rounded-md pl-1 min-h-[50px] max-h-[500px]  custom-scrollbar',
    props.className
  )
  useEffect(() => {
    adjustTextareaHeight()
  }, [value])

  const adjustTextareaHeight = () => {
    const textarea = textareaRef.current
    if (textarea) {
      textarea.style.overflowY = 'auto'
      textarea.style.height = 'auto'
      textarea.style.height = `${
        textarea.scrollHeight > 500 ? 500 : textarea.scrollHeight
      }px`
    }
  }
  const handleKeyUp = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      sendMsg()
      e.preventDefault()
      e.stopPropagation()
    }
  }
  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setValue(e.target.value)
  }
  useImperativeHandle(ref, () => {
    return {
      getValue: () => value,
      clearValue: () => setValue(''),
      setValue: (newValue: string) => {
        setValue(newValue)
        adjustTextareaHeight()
      },
    }
  })
  return (
    <textarea
      {...props.nodeProps}
      className={classes}
      ref={textareaRef}
      value={value}
      onChange={handleChange}
      onKeyUp={handleKeyUp}
    />
  )
})

export default AutoResizeTextarea
